import api from './config';
import { apiRequest } from './utils';

// 获取画布列表
export const getCanvasList = () => {
    return apiRequest(() => api.get('/list'));
};

// 创建新画布
export const createCanvas = (title, img) => {
    return apiRequest(() => api.post('/canvas', { title, img }));
};

// 删除画布
export const deleteCanvas = (canvasId) => {
    if (!canvasId) {
        return Promise.reject(new Error('画布ID不能为空'));
    }
    return apiRequest(() => api.delete(`/canvas/${canvasId}`));
};

// 更新画布
export const updateCanvas = (canvasId, title, img, zoom) => {
    return apiRequest(() => api.put('/canvas', { canvasId, title, img, zoom }));
};

// 获取画布快照
export const getCanvasSnapshot = (canvasId) => {
    if (!canvasId) {
        return Promise.reject(new Error('画布ID不能为空'));
    }
    console.log('请求画布快照, ID:', canvasId);
    return apiRequest(() => api.get(`/canvas-snapshots/${canvasId}`));
};

// 更新画布快照
export const updateCanvasSnapshot = (canvasId, snapshot) => {
    if (!canvasId) {
        return Promise.reject(new Error('画布ID不能为空'));
    }
    if (!snapshot) {
        return Promise.reject(new Error('画布数据不能为空'));
    }
    console.log('更新画布快照, ID:', canvasId);
    return apiRequest(() => api.post(`/canvas-snapshots/direct/${canvasId}`, snapshot));
};

// 获取分享码
export const getShareCode = (canvasId, expire) => {
    return apiRequest(() => api.get(`/canvas-shares/${canvasId}/${expire}`));
};

// 通过分享码加入协作
export const joinCollaboration = (shareCode) => {
    return apiRequest(() => api.post(`/canvas-shares/${shareCode}`));
};

// 获取特定画布
export const getCanvasById = (canvasId) => {
    return apiRequest(() => api.get(`/canvas/${canvasId}`));
};

// 退出协作
export const leaveCollaboration = (canvasId) => {
    if (!canvasId) {
        return Promise.reject(new Error('画布ID不能为空'));
    }
    return apiRequest(() => api.delete(`/canvas-collaborate/${canvasId}`));
};

// 取消分享
export const unshareCanvas = (canvasId) => {
    return apiRequest(() => api.delete(`/canvas-shares/${canvasId}`));
};

// 提交元素操作
export const submitElementOperation = (canvasId, operation) => {
    return apiRequest(() => api.post(`/canvas-operations/${canvasId}`, operation));
};
